<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>前端从入门到放弃5</title>
</head>
<body>
    
</body>
</html>
<script>
// 数组扁平化是指将一个多维数组变为一个一维数组
        var bbb = [1,2,3,[3,4,5,[7,8]]]
        const ccc = bbb.join(",").split(",");         //["1", "2", "3", "3", "4", "5", "7", "8"]
        const ddd = bbb.toString().split(",")	        //["1", "2", "3", "3", "4", "5", "7", "8"]
        console.log(ddd)  
        console.log([].concat(...bbb))			          //[1, 2, 3, 3, 4, 5, Array(2)]

       const arr = [1, [2, [3, [4, 5]]], 6];
       // => [1, 2, 3, 4, 5, 6]
     //方法零：拍平多维矩阵 
       const newsArr = [].concat(...arr)
       console.log(newsArr)   // [1, 2, 3, 4, 5, 6]

     //方法一：使用flat()
       const res1 = arr.flat(Infinity);   //[1, 2, 3, 4, 5, 6]
       console.log(res1)

     //方法二：利用正则
       const res2 = JSON.stringify(arr).replace(/\[|\]/g, '').split(',');
       console.log(res2)                   //["1", "2", "3", "4", "5", "6"]

     //方法三：正则改良版本
       const res3 = JSON.parse('[' + JSON.stringify(arr).replace(/\[|\]/g, '') + ']');
       console.log(res3)                   //[1, 2, 3, 4, 5, 6]

     //方法四：使用reduce
       const flatten = arr => {
        return arr.reduce((pre, cur) => {
            return pre.concat(Array.isArray(cur) ? flatten(cur) : cur);
        }, [])
        }
        const res4 = flatten(arr);
        console.log(res4)              //[1, 2, 3, 4, 5, 6]

     //方法五：函数递归
        const res5 = [];
        const fn = arr => {
        for (let i = 0; i < arr.length; i++) {
            if (Array.isArray(arr[i])) {
            fn(arr[i]);
            } else {
            res5.push(arr[i]);
            }
        }
        }
        fn(arr);              
        console.log(res5)              
        //[1, 2, 3, 4, 5, 6]

        //简写为flat（），接收一个数组，无论这个数组里嵌套了多少个数组，flatten最后都会把其变成一个一维数组(扁平化)
        const arr = [[1,2,3],[4,5,[6,7]]];
        const a = arr.flat(3);
        console.log(a); // [1, 2, 3, 4, 5, 6, 7]


        var entries = [1, [2, 5], [6, 7], 9];
        var flat_entries = [].concat(...entries); 
        // [1, 2, 5, 6, 7, 9]

//_______________________________________________________________________________________________________________
         var Arr = [1,2,3,4,5,6,7,8,9,10,11,12];
         var NewArr = group(Arr, 6);
         console.log(NewArr)  //[1,2,3,4,5,6],[7,8,9,10,11,12]






</script>